﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

using Perseus.Xml;

namespace Hetymine.Executioner.Data {
    public class HistoryItem : IData {
        public HistoryItem() {
            this.ExecutionDates = new List<DateTime>();
        }
        public HistoryItem(string command) : this(command, DateTime.Now) { }
        public HistoryItem(string command, DateTime dateTime) {
            this.Command = command;
            this.ExecutionDates = new List<DateTime>();
            this.ExecutionDates.Add(dateTime);
        }

        public string Command { get; set; }
        public List<DateTime> ExecutionDates { get; set; }

        #region IData
        public void Load(XElement element) {
            this.Command = element.Element("Command").ValueOrEmpty();

            if (element.Element("ExecutionDates") != null) {
                var dates = from d in element.Element("ExecutionDates").Elements("Date")
                               select d;

                foreach (var date in dates) {
                    try {
                        DateTime dt = DateTime.Parse(date.Value);                        
                        this.ExecutionDates.Add(dt);
                    }
                    catch {
                        App.Log("Error parsing history item date time '" + date.Value + "'.");
                        Executioner.Sounds.Error();
                    }
                }
            }
        }
        public XElement Save() {
            XElement xe = new XElement("Item");
            xe.Add(new XElement("Command", this.Command));
            
            XElement dxe = new XElement("ExecutionDates");
            foreach (DateTime dt in this.ExecutionDates) {
                dxe.Add(new XElement("Date", dt.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            xe.Add(dxe);

            return xe;
        }
        #endregion
    }
}
